/**
 * Created by gaojun on 17-3-7.
 */
import mqtt from 'mqtt';
import base from './base';
import config from '../config';
import * as robotRelationModel from '../models/robot_relation';
import * as robotModel from '../models/robot';


module.exports = [base];
module.exports.mqttListen = () => {
  // 建立服务器通知
  let serverClient = mqtt.connect(config.mqtt);
  serverClient.on('connect', () => {
    console.log('Mqtt server connect success');
    serverClient.subscribe('server');
  });

  serverClient.on('message', (topic, message) => {
    let info = JSON.parse(message.toString());
    if (!info.event) return;
    if (!info.rid) return;
    let handler = null;
    switch (info.event) {
      case 'close_anti_addiction':
        // 关闭防沉迷
        handler = robotModel.put(info.rid, { anti_addiction_status: 0 });
        break;
      case 'upgrade':
        // 升级
        // 更新数据库
        handler = robotModel.put(info.rid, { version: info.version });
        break;
      case 'sync_sound':
        // 同步播放
        handler = Promise.resolve();
        break;
      default:
        return;
    }
    // 查找该Robot关联的app，并发送消息
    handler.then(() => {
      let list = robotRelationModel.all(info.rid);
      list.forEach((row) => {
        serverClient.publish(`app/${row.user_id}`, message);
      });
    });
  });
  return serverClient;
};
